<script setup>

import MyNav from "@/components/MyNav.vue";
import {elConfirm, formatPermissions, getResponseData, uniqueElement} from "@/util";
import {listApi} from "@/api/PermissionApi";
import {onBeforeMount, ref} from "vue";
import router from "@/router";
import {getPermissionsApi, updatePermissionsApi} from "@/api/RoleApi";
import {ElMessage} from "element-plus";

// 路由中的角色主键
let roleId = router.currentRoute.value.query['roleId'];

/* ==================== 查询权限相关数据 ==================== */
let myPermissions = ref([]);
let allPermissions = ref([]);
let valueKeys = ref([]);

// 获取全部权限列表 + 当前角色的权限列表
function listData() {

  // 获取全部角色列表
  listApi().then(res => {
    let allPermissionsData = getResponseData(res);
    if (allPermissionsData) {

      // 隐藏父权限并合并一个 label 值用于显示权限完整标题（父权限 / 子权限）
      allPermissions.value = Object.values(allPermissionsData)
          .filter(e => e['pid'] !== 0)
          .map(e => Object.assign(e, {'label': `${e['parentPermission']['title']}  / ${e['title']}`}));

      // 获取我的权限列表
      getPermissionsApi(roleId).then(res => {
        let myPermissionsData = getResponseData(res);
        if (myPermissionsData) {
          myPermissions.value = myPermissionsData;
          // 构建key数组（清空数组，防止叠加）
          for (let i in myPermissions.value) {
            let permission = myPermissions.value[i];
            valueKeys.value.push(permission['id']);
          }
        }
      })
    }
  });
}

/**
 *
 */
function formatTitle(allPermissionsData){
  for(let i in allPermissionsData){
    let permission = allPermissionsData[i];
    if(permission['pid'] !== 0){
      permission['title'] = permission['parentPermission']['title'] + '/' + permission['title'];
    }
  }
  return allPermissionsData;
}

/* ==================== 确认修改权限 ==================== */
async function updatePermissions() {

  if (!await elConfirm('修改角色权限后需要重新登录本系统，确认修改吗？')) return;

  let permissionIds = [];

  // 获取每个权限的父权限
  for (let i in valueKeys.value) {
    // 子权限ID
    let subPermissionId = valueKeys.value[i];
    // 放入子权限ID
    permissionIds.push(subPermissionId);
    // 查询每个子权限的父权限
    for (let j in allPermissions.value) {
      let allPermission = allPermissions.value[j];
      if (allPermission['id'] === subPermissionId) {
        let parentPermissionId = allPermission['parentPermission']['id'];
        // 放入父权限ID
        if (permissionIds.indexOf(parentPermissionId) === -1) {
          permissionIds.push(parentPermissionId);
        }
      }
    }
  }

  let res = await updatePermissionsApi({
    'id': roleId,
    'permissionIds': permissionIds
  });
  let data = getResponseData(res);
  if (data) {
    ElMessage.success('权限修改成功，请重新登录！');
    setTimeout(() => router.push('/'), 1000);
  }
}
  // let permissionIds = [];
  // for (let i in allPermissions.value) {
  //   let allPermission = allPermissions.value[i];
  //   for (let j in valueKeys.value) {
  //     let valueKey = valueKeys.value[j];
  //     if (valueKey === allPermission['id']) {
  //       permissionIds.push(valueKey);
  //       for (let m in allPermission['subPermissions']) {
  //         permissionIds.push(allPermission['subPermissions'][m]['id']);
  //       }
  //     }
  //   }
  // }
  //
onBeforeMount(() => listData());

</script>

<template>
  <div class="role-permissions-body">

    <my-nav :items="[
    {'icon': 'Avatar', 'label': '用户管理', 'url': '/Role'},
    {'icon': 'UserFilled', 'label': '角色列表', 'url': '/Role'},
    {'icon': 'Flag', 'label': '权限列表'},
    ]"/>

    <el-divider/>

    <el-transfer v-if="valueKeys" v-model="valueKeys" :data="allPermissions"
                 filterable filter-placeholder="输入关键字"
                 :titles="['全部可选项', '当前已选项']"
                 :props="{'key': 'id', 'label': 'label'}"
                 :button-texts="['移除', '添加']"/>

    <el-button class="update-permissions-btn" type="primary"
               @click="updatePermissions">确认修改
    </el-button>
  </div>
</template>

<style scoped lang="scss">
.role-permissions-body {
  text-align: center; // 内容居中

  .update-permissions-btn {
    margin-top: 20px; // 上外边距
    width: 53%; // 宽度
  }
}

/* 修改EL穿梭框高度 */
:deep(.el-transfer-panel), :deep(.el-transfer-panel__body) {
  height: 500px; // 高度
  width: 250px;
}
</style>